package com.meixiang.activity.account.myShopper;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.adapter.personalCenter.OrderEvaluationPhotoAdapter;
import com.meixiang.dialog.SelectDialog;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbFileUtils;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.ClearEditText;
import com.meixiang.view.TitleView;
import com.meixiang.view.photoSelectActivity.util.Bimp;
import com.meixiang.view.pickerView.OptionsPickerView;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author yinsujun  Created at 2016/5/9 19:20
 *         订单 退换售后
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class OrderSaleActivity extends BaseActivity {
    @Bind(R.id.title)
    TitleView title;
    @Bind(R.id.order_sale_tv_sales_return)
    TextView tvSalesReturn;
    @Bind(R.id.order_sale_iv_return)
    ImageView ivReturn;
    @Bind(R.id.order_sale_tv_refund)
    TextView tvRefund;
    @Bind(R.id.order_sale_iv_refund)
    ImageView ivRefund;
    @Bind(R.id.order_sale_tv_select_reason)
    TextView tvSelectReason;
    @Bind(R.id.order_sale_et_problem_details)
    ClearEditText etProblemDetails;
    @Bind(R.id.order_sale_linear_photo_printing)
    LinearLayout linearPhotoPrinting;
    @Bind(R.id.order_sale_linear_refund)
    LinearLayout linearRefund;
    @Bind(R.id.order_sale_linear_return)
    LinearLayout linearReturn;
    @Bind(R.id.order_sale_title)
    View orderSaleTitle;
    @Bind(R.id.order_sale_tv_not_refund)
    TextView tvNotRefund;
    @Bind(R.id.order_sale_tv_receiving)
    TextView tvReceiving;
    @Bind(R.id.order_sale_iv_receiving)
    ImageView ivReceiving;
    @Bind(R.id.order_sale_tv_not_received)
    TextView tvNotReceived;
    @Bind(R.id.order_sale_iv_not_received)
    ImageView ivNotReceived;
    @Bind(R.id.order_sale_tv_return_reason)
    TextView tvReturnReason;
    @Bind(R.id.order_sales_linear_return)
    LinearLayout linearSalesReturn;
    @Bind(R.id.order_sale_linear_refund_select)
    LinearLayout linearRefundSelect;
    @Bind(R.id.order_sale_bt_commit)
    Button btConfirm;
    @Bind(R.id.order_sale_et_money)
    ClearEditText etMoney;
    @Bind(R.id.order_sale_tv_money)
    TextView tvRefundMoney;
    @Bind(R.id.order_sale_recycler)
    RecyclerView recyclerView;
    private OptionsPickerView pickerView;
    private ArrayList<String> customList;
    private ArrayList<String> imageList;
    private DeleteSelectPhotoBroad broadCast;

    private String orderId,recId,orderName;
    private String goodsPrice;
    private String refundReason = "", refundId = "",
            serviceType="1" ,//服务类型（1退货，2退款)
            receiveStatus="" //收货状态（1收货，2未收货）
             ;
    public OrderEvaluationPhotoAdapter gridAdapter;
    private static final int CAMERA_CODE = 0x00; // 拍照的权限
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_sale);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        setTitle("退换售后");
    }

    @Override
    protected void initView() {
        orderId=getIntent().getStringExtra("orderId");
        recId=getIntent().getStringExtra("recId");
        orderName=getIntent().getStringExtra("orderName");
        gridAdapter=new OrderEvaluationPhotoAdapter(context,orderName);
        GridLayoutManager gridLayoutManager=new GridLayoutManager(context,4);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(gridAdapter);
        registerBroadCast();
    }

    private void registerBroadCast(){
        broadCast=new DeleteSelectPhotoBroad();
        IntentFilter intentFilter=new IntentFilter(GlobalType.EVALUATE_ORDER_DELETE_PHOTO);
        registerReceiver(broadCast, intentFilter);
    }
    @Override
    protected void setData() {
        imageList=new ArrayList<>();
        getRefundInfo();
        getRefundReason();
    }


    @OnClick({R.id.order_sale_tv_sales_return, R.id.order_sale_linear_refund, R.id.order_sale_tv_receiving, R.id.order_sale_tv_not_received
            , R.id.order_sale_tv_select_reason, R.id.order_sale_bt_commit,R.id.order_sale_linear_photo_printing})
    void click(View view) {
        if (view.equals(tvSalesReturn)) {
            //我要退货
            serviceType="1";
            receiveStatus="";
            setSelectView(tvSalesReturn, tvRefund, ivReturn, ivRefund, 1);
            linearRefundSelect.setVisibility(View.GONE);
            tvSelectReason.setText(R.string.order_select_reason);
            tvReturnReason.setText("退款原因");
            refundId="";
            tvSalesReturn.setBackground(ContextCompat.getDrawable(context, R.drawable.order_sale_red_select_background));
            linearRefund.setBackground(ContextCompat.getDrawable(context, R.drawable.order_sale_gray_select_background));
        } else if (view.equals(linearRefund)) {
            //我要退款
            receiveStatus="1";
            serviceType="2";
            setSelectView(tvRefund, tvSalesReturn, ivRefund, ivReturn, 1);
            tvSelectReason.setText(R.string.order_select_reason);
            refundId="";
            linearRefundSelect.setVisibility(View.VISIBLE);
            linearRefund.setBackground(ContextCompat.getDrawable(context, R.drawable.order_sale_red_select_background));
            tvSalesReturn.setBackground(ContextCompat.getDrawable(context, R.drawable.order_sale_gray_select_background));
            tvReturnReason.setText("收货状态");
        } else if (view.equals(tvReceiving)) {
            //收货
            receiveStatus="1";
            setSelectView(tvReceiving, tvNotReceived, ivReceiving, ivNotReceived, 0);
        } else if (view.equals(tvNotReceived)) {
            //未收货
            receiveStatus="2";
            setSelectView(tvNotReceived, tvReceiving, ivNotReceived, ivReceiving, 0);
        } else if (view.equals(tvSelectReason)) {
            if(reasons!=null&&reasons.size()>0){
                pickerView.show();
            }else{
                Tool.showTextToast(context,"未获取退款原因");
            }
        } else if (view.equals(btConfirm)) {
            submitApply();
        }else if(view.equals(linearPhotoPrinting)){
            if(imageList.size()>=GlobalType.ORDER_PICTURE_COUNT){
                Tool.showTextToast(context,"最多只能选择"+GlobalType.ORDER_PICTURE_COUNT+"张");
                return;
            }
            new SelectDialog(context, new String[]{"拍照上传", "相册选择"}, new SelectDialog.IResultListener() {
                @Override
                public void SelectResult(int result) {
                    if (result == 0) {
                        //拍照
                        if (Build.VERSION.SDK_INT >= 23) {
                            MPermissions.requestPermissions(OrderSaleActivity.this, CAMERA_CODE, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA});
                        }else{
                            photoGraph();
                        }
                    } else {
                        //手机相册
                        localImage();
                    }
                }
            });
        }
    }

    private void getRefundInfo(){
        String url=Config.SERVER_URL+"refund/refundGoodsService";
        HttpParams params=new HttpParams();
        params.put("recId",recId);
        params.put("orderId",orderId);
        HttpUtils.post(url, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                goodsPrice=result.optString("goodsPrice");
                tvRefundMoney.setText("最多"+goodsPrice+"元");
//                String orderId=result.optString("orderId");
//                String recId=result.optString("recId");

            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);

            }
        });
    }

    private ArrayList<HashMap<String, String>> reasons;
    private void getRefundReason() {
        String url = Config.GET_ORDER_REFUND_REASON;
        reasons = new ArrayList<>();
//        JsonBean resultData = VirtualDataHelper.getResultData(context, "order/refundReason.json");
        HttpUtils.post(url, new HttpParams(), new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                JSONArray refundReasonList = result.optJSONArray("refundReasonList");
                for (int i = 0; i < refundReasonList.length(); i++) {
                    HashMap<String, String> reason = new HashMap<>();
                    JSONObject jsonObject = refundReasonList.optJSONObject(i);
                    String reasonId = jsonObject.optString("reasonId");
                    String reasonInfo = jsonObject.optString("reasonInfo");
                    reason.put(reasonId, reasonInfo);
                    reasons.add(reason);
                    initPickerView(reasons);
                }
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);

            }
        });

    }

    private void submitApply() {

        if(AbStrUtil.isEmpty(refundReason)){
            Tool.showTextToast(context,"请选择退款原因");
            return;
        }
        if(AbStrUtil.isEmpty(etMoney.getText().toString().trim())){
            Tool.showTextToast(context,"请输入退款金额");
            return;
        }
        if(Double.parseDouble(etMoney.getText().toString().trim())<=0){
            Tool.showTextToast(context,"金额不能为0");
            return;
        }
        if(!AbStrUtil.isEmpty(goodsPrice)){
            Double price=Double.parseDouble(goodsPrice);
            Double money=Double.parseDouble(etMoney.getText().toString().trim());
            if(money>price){
                Tool.showTextToast(context,"不能大于最大退款金额");
                return;
            }

        }else{
            Tool.showTextToast(context,"未获取退款金额");
        }
//        if(AbStrUtil.isEmpty(etProblemDetails.getText().toString().trim())){
//            Tool.showTextToast(context,"请输入问题描述");
//            return;
//        }

        String url = Config.SUBMIT_APPLY_REFUND;
        /**
         * images 	String 	必填 			图片
         orderInfo 	String 	必填 			问题描述
         refundAmount 	String 	必填 	5.5 		退款金额double类型
         refundReason 	String 	必填 			退款原因
         reasonId 	Integer 	必填 	1 		退款原因Id
         receiveStatus 	Integer 	必填 	1 		收获状态（1收货，2未收货）
         serviceType 	String 	必填 	1 		服务类型（1退货，2退款）
         recId 	Integer 	必填 	1 		订单商品id
         orderId 	Integer 	必填
         */
        HttpParams params = new HttpParams();
//        params.put("images", "images");
        params.put("orderInfo", etProblemDetails.getText().toString().trim());
        params.put("refundAmount", etMoney.getText().toString().trim());
        params.put("refundReason", refundReason);
        params.put("reasonId", refundId);
        params.put("receiveStatus", receiveStatus);
        params.put("serviceType", serviceType);
        params.put("recId", recId);
        params.put("orderId", orderId);
        HttpUtils.post(url, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(context, message);
                if(result!=null){
                    String refundId=result.optString("returnId");
                    if(!AbStrUtil.isEmpty(refundId)){
                        uploadImage(refundId);
                    }
                }
                notifyOrderList();
                OrderSaleActivity.this.finish();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);
            }
        });
    }


    private void uploadImage(String refundId){
        String url=Config.SERVER_URL+"refund/imageFileReceive";
        HttpParams params=new HttpParams();
        params.put("refundId",refundId);
        if(imageList.size()>0){
            List<File> fileList=new ArrayList<>();
            for(int i=0;i<imageList.size();i++){
                File compressFile = getCompressFile(imageList.get(i));
                if(compressFile!=null){
                    fileList.add(new File(imageList.get(i)));
                }
            }
            HttpUtils.postFiles(url, params, "imageFile", fileList, new HttpCallBack(this) {
                @Override
                public void onSucceed(JSONObject result, String code, String message) {
//                    Tool.showTextToast(context,message);
                }

                @Override
                public void onError(String code, String message) {
                    Tool.showTextToast(context,message);
                }
            });
        }
    }

    /**
     * 压缩图片上传
     * @param file1
     * @return
     */
    private File getCompressFile(String file1){
        Log.e(TAG,"文件大小==="+ AbFileUtils.getFileSizeFor(new File(file1)));
        try {
            Bitmap bitmap = Bimp.revitionImageSize(file1);
            if(bitmap==null){
                Log.e(TAG,"图片转bitmap失败");
                return null;
            }else{
                Log.e(TAG,"图片转bitmap成功");
                Bitmap bitmap1 = AbFileUtils.compressImage(bitmap);
                //创建新的照片
                File mFolder = new File(Environment.getExternalStorageDirectory(), Config.base_data_path + "/mx");
                if (!mFolder.exists()) {
                    mFolder.mkdirs();
                }
                String filePath=file1;
                if(filePath.contains(".")){
                    filePath=filePath.substring(filePath.lastIndexOf("/")+1,filePath.indexOf("."));
                }
                String imgName = mFolder.getAbsolutePath() + filePath+ ".jpg";
                File compressPath=new File(imgName);
                if(compressPath.exists()){
                    Log.e(TAG,"压缩文件路径存在=="+compressPath.getAbsolutePath());
                    return compressPath;
                }else{
                    File file = AbFileUtils.saveFile(bitmap1, imgName);
                    Log.e(TAG,"压缩文件路径=="+file.getAbsolutePath());
                    return file;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private OptionsPickerView initPickerView(final ArrayList<HashMap<String, String>> reasons) {
        customList = new ArrayList<>();
        //选项选择器
        pickerView = new OptionsPickerView(this);

//        String test[]={"伪劣产品","退运费","大小/尺寸不符","我不想要了","质量问题","卖家发错货","少件漏发","假冒产品","其他问题"};
//        for(int i=0;i<test.length;i++){
//            customList.add(test[i]);
//        }

        for (int i = 0; i < reasons.size(); i++) {
            HashMap<String, String> reasonList = reasons.get(i);
            Iterator<Map.Entry<String, String>> iterator = reasonList.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                customList.add(next.getValue());
            }
        }

        //一级
        pickerView.setPicker(customList);
        pickerView.setTitle("退款原因");
        pickerView.setCyclic(false);
        //设置默认选中的三级项目
        //监听确定选择按钮
        pickerView.setSelectOptions(1);
        pickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
//                String reason = customList.get(options1);
                HashMap<String, String> selectReason = reasons.get(options1);
                Iterator<Map.Entry<String, String>> iterator = selectReason.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> next = iterator.next();
                    Log.e("OrderSale", next.getKey() + "===退款选择原因===" + next.getValue());
                    refundId = next.getKey();
                    refundReason = next.getValue();
                    tvSelectReason.setText(next.getValue());

                }
            }
        });
        return pickerView;
    }

    private void setSelectView(TextView selectView, TextView normalView, ImageView selectImageView, ImageView normalImageView, int type) {
        selectView.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
        selectImageView.setVisibility(View.VISIBLE);
        normalView.setTextColor(ContextCompat.getColor(context, R.color.black_6));
        normalImageView.setVisibility(View.GONE);
        if (type == 0) {
            selectView.setBackground(ContextCompat.getDrawable(context, R.drawable.order_sale_red_select_background));
            normalView.setBackground(ContextCompat.getDrawable(context, R.drawable.order_sale_gray_select_background));
        }
    }


    @Override
    public void onClick(View v) {


    }
    /**
     * 图片文件选择
     */

    private void localImage() {
        Intent intent = new Intent(context,PhotoFileEvaluateActivity.class);
//        intent.putExtra("photoType", "");
        if(imageList.size()>0){
            intent.putExtra("selectImageSize",imageList.size());
        }
        startActivityForResult(intent,100);

    }

    /**
     * 拍照
     */
    private File imgFile;//相机拍照存放地址

    private void photoGraph() {
        //判断内存卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //创建文件夹
            File mFolder = new File(Environment.getExternalStorageDirectory(), Config.base_data_path + "/mx");
            //判断是否存在，不存在则创建
            if (!mFolder.exists()) {
                mFolder.mkdirs();
            }
            //删除存在的照片
            File files[] = mFolder.listFiles(); // 声明目录下所有的文件 files[];
            for (int i = files.length - 1; i >= 0; i--) { // 遍历目录下所有的文件
                files[i].delete();// 删除
            }
            //创建新的照片
            String imgName = "mx_" + System.currentTimeMillis() + ".png";
            imgFile = new File(mFolder, imgName);
            //打开相机
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            captureIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            //保存路径
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
            Log.e("TAG","输出照相路径==="+Uri.fromFile(imgFile));
            startActivityForResult(captureIntent, 101);
        } else {
            AbToastUtil.showToast(context, context.getResources().getString(R.string.account_manage_no_sd_card));
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==100&&resultCode==200){
            //相册选择
            ArrayList<String> fileName = data.getStringArrayListExtra("fileName");
            imageList.addAll(fileName);
            gridAdapter.addPhoto(imageList);
        }else if(requestCode==101&&resultCode==RESULT_OK){
            //拍照
//                String fileName = imgFile.getAbsolutePath();
//                 Bitmap assetsBitmap = Tool.getAssetsBitmap(context, fileName);
//                ImageItem takePhoto = new ImageItem();
//                takePhoto.setBitmap(assetsBitmap);
//                takePhoto.setImagePath(fileName);
//                allUploadFile.add(imgFile);
//                Bimp.tempSelectBitmap.add(takePhoto);
//                evaluationAdapter.addSelectImage(Bimp.tempSelectBitmap);
            if(!AbStrUtil.isEmpty( imgFile.getAbsolutePath())) {
                String path = imgFile.getAbsolutePath();
                imageList.add(path);
                gridAdapter.addPhoto(imageList);
            }

        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @PermissionGrant(CAMERA_CODE)
    public void requestSdcardSuccess() {
        photoGraph();
    }

    @PermissionDenied(CAMERA_CODE)
    public void requestSdcardFailed() {
        Toast.makeText(activity, "无法启动系统照相机!", Toast.LENGTH_SHORT).show();
    }

    private class DeleteSelectPhotoBroad extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int position=intent.getIntExtra("position",0);
//            int orderPosition=intent.getIntExtra("orderPosition",0);
            gridAdapter.deletePhoto(position);


        }
    }

    /**
     * 刷新订单列表
     */
    private void notifyOrderList(){
        Intent intent=new Intent(GlobalType.ORDER_DETAIL_OPERATION);
        sendBroadcast(intent);
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadCast);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getKeyCode()==KeyEvent.KEYCODE_BACK){
            if(pickerView!=null&&pickerView.isShowing()){
                pickerView.dismiss();
                return true;
            }else{
                this.finish();
            }
        }
        return true;

    }
}
